package nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/25 14:45
 */
public class BlockingNIOTest2 {
    // 客户端
    @Test
    public void testClient() {
        try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
             FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1.jpg"), StandardOpenOption.READ)) {
            System.out.println("connected to server");
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (fileChannel.read(buffer) != -1) {
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
            }

            socketChannel.shutdownOutput();
            System.out.println("send data over, waiting for message");
            // 接收服务端的信息
            StringBuilder message = new StringBuilder();
            int len = 0;
            while ((len = socketChannel.read(buffer)) != -1) {
                buffer.flip();
                message.append(new String(buffer.array(), 0, len));
                buffer.clear();
            }

            System.out.println(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //服务端
    @Test
    public void testServer() {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
             FileChannel fileChannel = FileChannel.open(Paths.get("D:\\2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
            serverSocketChannel.bind(new InetSocketAddress(9898));
            System.out.println("listening...");
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println("accept a connection");
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(buffer) != -1) {
                buffer.flip();
                fileChannel.write(buffer);
                buffer.clear();
            }
            System.out.println("transport terminate, send a message");
            // 发送反馈信息
            String message = "accept success!";
            buffer.put(message.getBytes());
            buffer.flip();
            socketChannel.write(buffer);

            socketChannel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
